package com.tanhua.server.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.RSA;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.io.File;
/**
 * 用于读取RSA所存储的公钥和私钥的文件 如果文件不存在则生成文件
 */
@Getter
@Service
public class RSAService {

    private String publicKeyStr;

    @Value("${tanhua.rsa.dir}")
    private String rsaFileDir;

    @PostConstruct
    public void init() {
        String filePath=rsaFileDir + File.separator + "rsa.pub";
        File publicKeyFile = new File(filePath);
        if (FileUtil.exist(publicKeyFile)) {
            this.publicKeyStr = FileUtil.readString(publicKeyFile, CharsetUtil.CHARSET_UTF_8);
        }
        //判断
        if (StrUtil.isEmpty(this.publicKeyStr)) {
            //如果读取不到公钥 则不能让server系统启动
            throw new RuntimeException(StrFormatter.format("读取公钥文件失败请检查文件是否存在,filePath:{}",filePath));
        }

    }
}
